package org.example.hikvisiontest.service.impl;

import cn.hutool.core.util.StrUtil;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.example.hikvisiontest.Entity.CameraInfoEntity;
import org.example.hikvisiontest.config.CameraConfig;
import org.example.hikvisiontest.enums.CameraIP;
import org.example.hikvisiontest.hksdk.HCNetSDK;
import org.example.hikvisiontest.service.HikVisionService;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * @创建人 qianchengcheng
 * @创建时间 2022/4/25
 * @描述
 */
@Log4j2
@Service
public class HikVisionServiceImpl implements HikVisionService {

    @Resource
    private HCNetSDK hCNetSDK;

    @Resource
    private CameraConfig cameraConfig;
    static ArrayList<CameraInfoEntity> cameraInfoEntities = new ArrayList<>();
    @PostConstruct
    public void cameraInfoInit() {
        File file = new File(cameraConfig.getSavePath());
//如果文件夹不存在则创建

        if (!file.exists() && !file.isDirectory()) {
            log.info("相机抓拍文件夹路径不存在");
            file.mkdir();
        }

        ArrayList<CameraInfoEntity> cameraInfoEntities = new ArrayList<>();

        for (String ip : CameraIP.toIpList()) {
            CameraInfoEntity cameraInfoEntity = new CameraInfoEntity(ip, cameraConfig.getPort(), cameraConfig.getName(), cameraConfig.getPassword());
            cameraInfoEntities.add(cameraInfoEntity);
        }
        this.loginDevices(cameraInfoEntities);

    }

    @Override
    public void loginDevices(ArrayList<CameraInfoEntity> cameras) {
        for (CameraInfoEntity cameraInfoEntity : cameras) {
            // 创建设备登录信息和设备信息对象
            HCNetSDK.NET_DVR_USER_LOGIN_INFO loginInfo = new HCNetSDK.NET_DVR_USER_LOGIN_INFO();
            HCNetSDK.NET_DVR_DEVICEINFO_V40 deviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V40();

            // 设置设备IP地址
            byte[] deviceAddress = new byte[HCNetSDK.NET_DVR_DEV_ADDRESS_MAX_LEN];
            byte[] ipBytes = cameraInfoEntity.getIp().getBytes();
            System.arraycopy(ipBytes, 0, deviceAddress, 0, Math.min(ipBytes.length, deviceAddress.length));
            loginInfo.sDeviceAddress = deviceAddress;

            // 设置用户名和密码
            byte[] userName = new byte[HCNetSDK.NET_DVR_LOGIN_USERNAME_MAX_LEN];
            byte[] password = cameraInfoEntity.getPassword().getBytes();
            System.arraycopy(cameraInfoEntity.getName().getBytes(), 0, userName, 0, Math.min(cameraInfoEntity.getName().length(), userName.length));
            System.arraycopy(password, 0, loginInfo.sPassword, 0, Math.min(password.length, loginInfo.sPassword.length));
            loginInfo.sUserName = userName;

            // 设置端口和登录模式
            loginInfo.wPort = (short) cameraInfoEntity.getPort();
            loginInfo.bUseAsynLogin = false; // 同步登录
            loginInfo.byLoginMode = 0; // 使用SDK私有协议

            // 执行登录操作
            int userID = hCNetSDK.NET_DVR_Login_V40(loginInfo, deviceInfo);
            if (userID == -1) {
                System.err.println("登录失败，错误码为: " + hCNetSDK.NET_DVR_GetLastError());
                return;
            } else {
                log.info(cameraInfoEntity.getIp() + " 设备登录成功！");
                // 处理通道号逻辑
                int startDChan = deviceInfo.struDeviceV30.byStartDChan;
                cameraInfoEntity.setStartDChan(startDChan);

            }
            cameraInfoEntity.setUserId(userID);
            cameraInfoEntities.add(cameraInfoEntity);

        }


    }


    //手动抓拍
    @Override
    public boolean catchImageByIp(String ip) {
        Optional<CameraInfoEntity> first = cameraInfoEntities.stream().filter(item -> item.getIp().equals(ip)).findFirst();
        CameraInfoEntity cameraInfoEntity = first.get();
        HCNetSDK.NET_DVR_JPEGPARA strJpeg = new HCNetSDK.NET_DVR_JPEGPARA();
        strJpeg.wPicQuality = 1; //图像参数
        strJpeg.wPicSize = 2;
        List<String> split1 = StrUtil.split(cameraInfoEntity.getIp(), ".");

        if (split1.isEmpty()) {
            return false;
        }

       String filePath=cameraConfig.getSavePath()+"//"+CameraIP.findEnumByIP(ip)+"//";
        File file = new File(filePath);
        if (!file.exists() && !file.isDirectory()) {
            log.info("相机抓拍文件夹路径不存在");
            file.mkdir();
        }
         filePath=filePath+    UUID.randomUUID() + ".jpg";

        hCNetSDK.NET_DVR_CaptureJPEGPicture(cameraInfoEntity.getUserId(), 1, strJpeg, filePath);
        return hCNetSDK.NET_DVR_GetLastError() == 0;
    }
}

